<template>
  <view class="weight-page">
    <!-- 权重概览 -->
    <view class="weight-overview">
      <view class="overview-item" :class="{ active: activeTab === 'unused' }" @click="switchTab('unused')">
        <view class="value unused">尚未使用值：{{ weightInfo.unused_amount || 0 }}</view>
        <view class="underline" v-if="activeTab === 'unused'"></view>
      </view>
      
      <view class="overview-item" :class="{ active: activeTab === 'total' }" @click="switchTab('total')">
        <view class="value total">累计值：{{ weightInfo.total_amount || 0 }}</view>
        <view class="underline" v-if="activeTab === 'total'"></view>
      </view>
    </view>
    
    <!-- 权重记录列表 -->
    <scroll-view 
      class="scroll-container"
      scroll-y="true"
      @scrolltolower="onLoadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
  
      
      <view class="list-content" v-if="weightFlowList.length > 0">
        <view 
          class="list-item" 
          v-for="(item, index) in weightFlowList" 
          :key="index"
        >
          <view class="item-left">
            <view class="date-time">{{ formatDateTime(item.created_at) }}</view>
            <view class="user-info" v-if="item.num > 0">
              <view class="avatar">
                <image :src="item.adopt_user_avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              </view>
              <view class="user-details">
                <view class="user-id">ID: {{ item.adopt_user_id || '12345' }}</view>
                <view class="user-nickname">昵称: {{ getUserNickname(item.adopt_user_id) }}</view>
              </view>
            </view>

          </view>
          
          <view class="item-right">
            <view 
              class="change-value" 
              :class="{ 'positive': item.num > 0, 'negative': item.num < 0 }"
            >
              {{ item.num > 0 ? '+' : '' }}{{ item.num }}
            </view>
          </view>
        </view>
      </view>
      
      <view class="empty-state" v-else>
        <view class="empty-text">暂无权重变更记录</view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && weightFlowList.length > 0">
        <uni-load-more :status="loadingStatus"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getUserWeight, getWeightFlowList } from '@/api/weight';

// 响应式数据
const activeTab = ref('unused');
const weightInfo = reactive({
  unused_amount: 0,
  total_amount: 0
});

const weightFlowList = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(20);
const hasMore = ref(true);
const loadingStatus = ref('more');
const refreshing = ref(false);

// 用户昵称映射（实际项目中应该从接口获取）
const userNicknames = ref({
  '12345': '张小明',
  '1331': '李小红',
  '2001': '王大力',
  '2002': '赵美丽',
  '2003': '陈小华',
  '2004': '刘小芳',
  '2005': '杨小军'
});

// 方法
const goBack = () => {
  uni.navigateBack();
};

const switchTab = (tab: string) => {
  activeTab.value = tab;
  // 切换标签时重新获取数据
  fetchWeightFlowList(true);
};

const formatDateTime = (datetime: string | number) => {
  // 如果已经是格式化的字符串，直接返回（去掉秒数）
  if (typeof datetime === 'string') {
    // 格式: "2025-04-15 08:00:00" -> "2025-04-15 08:00"
    return datetime.substring(0, 16);
  }
  
  // 如果是时间戳，进行转换
  const date = new Date(datetime * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

const getUserNickname = (userId: number) => {
  // 如果item中有用户信息，直接使用
  const item = weightFlowList.value.find(item => item.adopt_user_id === userId);
  if (item && item.adopt_user_nickname) {
    return item.adopt_user_nickname;
  }
  return userNicknames.value[String(userId) as keyof typeof userNicknames.value] || '未知用户';
};

// 获取权重信息
const fetchWeightInfo = async () => {
  try {
    const res = await getUserWeight({});
    if (res.result === 1) {
      Object.assign(weightInfo, res.data);
    } else {
      console.error('获取权重信息失败:', res.msg);
    }
  } catch (error) {
    console.error('获取权重信息失败:', error);
  }
};

// 获取权重变更记录
const fetchWeightFlowList = async (isRefresh = false) => {
  if (isRefresh) {
    currentPage.value = 1;
    weightFlowList.value = [];
    hasMore.value = true;
  }
  
  if (!hasMore.value) return;
  
  loadingStatus.value = 'loading';
  
  try {
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    
    // 如果是累计值模式，传递type=1
    if (activeTab.value === 'total') {
      params.type = 1;
    }
    
    const res = await getWeightFlowList(params);
    
    if (res.result === 1) {
      const { list, total } = res.data;
      
      if (isRefresh) {
        weightFlowList.value = list;
      } else {
        weightFlowList.value.push(...list);
      }
      
      hasMore.value = weightFlowList.value.length < total;
      currentPage.value++;
      
      loadingStatus.value = hasMore.value ? 'more' : 'noMore';
    } else {
      console.error('获取权重记录失败:', res.msg);
      loadingStatus.value = 'more';
    }
    
  } catch (error) {
    console.error('获取权重记录失败:', error);
    loadingStatus.value = 'more';
  }
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  await fetchWeightInfo();
  await fetchWeightFlowList(true);
  refreshing.value = false;
};

// 上拉加载更多
const onLoadMore = () => {
  if (hasMore.value && loadingStatus.value === 'more') {
    fetchWeightFlowList();
  }
};

// 生命周期
onMounted(() => {
  fetchWeightInfo();
  fetchWeightFlowList(true);
});

onShow(() => {
  fetchWeightInfo();
});
</script>

<style lang="scss" scoped>
.weight-page {
  height: 100vh;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

.weight-overview {
  display: flex;
  padding: 20rpx 0;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  flex-shrink: 0;
  
    .overview-item {
      flex: 1;
      text-align: center;
      position: relative;
      padding: 20rpx 0;
      
      .value {
        font-size: 36rpx;
        font-weight: bold;
        color: #999999;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:active {
          opacity: 0.7;
        }
      }
      
      &.active {
        .value {
          color: #4CAF50 !important;
          transform: scale(1.02);
        }
      }
      
      .underline {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background-color: #4CAF50;
        border-radius: 2rpx;
      }
    }
}

.scroll-container {
  flex: 1;
  height: 0;
}

.list-content {
  background-color: #ffffff;
  
  .list-item {
    display: flex;
    align-items: flex-start;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-left {
      flex: 1;
      
      .date-time {
        font-size: 28rpx;
        color: #666666;
        margin-bottom: 20rpx;
      }
      
      .user-info {
        display: flex;
        align-items: center;
        
        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 20rpx;
        }
        
        .avatar image {
          width: 100%;
          height: 100%;
        }
        
        .user-details {
          .user-id {
            font-size: 26rpx;
            color: #333333;
            margin-bottom: 8rpx;
          }
          
          .user-nickname {
            font-size: 24rpx;
            color: #666666;
          }
        }
      }
    }
    
    .item-right {
      .change-value {
        font-size: 32rpx;
        font-weight: bold;
        text-align: right;
        
        &.positive {
          color: #4CAF50;
        }
        
        &.negative {
          color: #F44336;
        }
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999999;
  }
}

.load-more {
  padding: 20rpx 0;
}

.list-header {
  padding: 30rpx 30rpx 20rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .header-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 10rpx;
  }
  
  .header-subtitle {
    font-size: 24rpx;
    color: #999999;
  }
}

.item-details {
  margin-top: 20rpx;
  
  .detail-row {
    display: flex;
    margin-bottom: 10rpx;
    
    .label {
      font-size: 26rpx;
      color: #666666;
      width: 140rpx;
    }
    
    .value {
      font-size: 26rpx;
      color: #333333;
      flex: 1;
    }
  }
}
</style>
